package com.example.weather_demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView responseText;
    private EditText weather;
    private EditText city;
    private EditText temperature;
    private String Weather;
    private String CityName;
    private String Tempeature;
    private Button btn_save;
    private Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response);
        weather = (EditText) findViewById(R.id.Weather);
        city = (EditText) findViewById(R.id.City);
        temperature = (EditText) findViewById(R.id.Temperature);
        sendRequest.setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String filename = "text2";
                String filecontent = responseText.getText().toString();
                FileOutputStream out = null;
                try {
                    out = context.openFileOutput(filename, Context.MODE_PRIVATE);
                    out.write(filecontent.getBytes("UTF-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建一个OkHttp实例
                    OkHttpClient client = new OkHttpClient();
                    //创建Request对象发起请求
                    Request request = new Request.Builder().url("https://api.seniverse.com/v3/weather/" +
                            "now.json?key=SrvH71t8JeTOXNLJP&location=beijing&language=zh-Hans&unit=c").build();
                    //创建call对象并调用execute获取返回的数据
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    //显示原始数据和解析后的数据
                    showResPonse(responseData);
                    //解析JSON数据
                    parseJSONWithJSONObject(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //用JSONObect解析JSON数据
    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            //得到键为results的JSONArray
            JSONArray results = jsonObject.getJSONArray("results");
            //得到键值为"now"的JSONObject
            JSONObject now = results.getJSONObject(0).getJSONObject("now");
            //得到键值为location的JSONObject
            JSONObject location = results.getJSONObject(0).getJSONObject("location");
            //得到"now"键值的JSONObject下的"text"属性,即天气信息
            Weather = now.getString("text");
            //获得城市名
            CityName = location.getString("name");
            //获取温度
            Tempeature = now.getString("temperature");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showResPonse(final String response) {
        //切换到主线程,ui界面的更改不能出现在子线程,否则app会崩溃
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
                city.setText(CityName);
                weather.setText(Weather);
                temperature.setText(Tempeature);
            }
        });
    }
}
